<template>
  <a-select
    :modelValue="innerValue"
    @update:modelValue="handleValueChange"
    :placeholder="placeholder"
    :showSearch="true"
    :allowClear="true"
    :filter-option="false"
    @search="handleSearch"
    @popupScroll="handlePopupScroll"
    :loading="loading"
    :mode="props.mode === 'multiple' ? 'multiple' : undefined"
    v-bind="$attrs"
  >
    <a-select-option v-for="item in options" :key="item.value" :value="item.value" :disabled="item.disabled">
      {{ item.label }}
    </a-select-option>

    <template #notFoundContent v-if="loading">
      <a-spin size="small" />
    </template>
  </a-select>
</template>

<script setup>
  import { onMounted, ref, watch, reactive } from 'vue'
  import { debounce } from 'lodash-es'
  import { message } from 'ant-design-vue'
  import { ZZB_ENABLE_STATUS_ENUM } from '/@/constants/system/system-const.js'
  import { dataSubDictionariesApi } from '/@/api/business/b-operation/data-dictionaries/data-sub-dictionaries-api.js'
  import { dataDictionariesApi } from '/@/api/business/b-operation/data-dictionaries/data-dictionaries-api.js'
  import { isEmpty } from 'lodash-es'
  import * as DICT from '/@/constants/dict'

  // console.log('DataDictionariesSelect==》', DICT)

  const props = defineProps({
    modelValue: {
      type: [String, Number, Object, Array],
      default: null,
    },
    mode: {
      type: String,
      default: 'single',
    },
    placeholder: {
      type: String,
      default: '请选择',
    },
    queryParams: {
      type: Object,
      default: () => ({}),
    },
    queryParamKey: {
      type: String,
      default: 'nameLikeLeft',
    },
    responseAdapter: {
      type: Function,
      default: (res) => ({
        ...res,
        data: res.data,
        total: res.total,
      }),
    },
    // 新增属性，用于指定 value 字段名
    valueField: {
      type: String,
      default: 'value',
    },
    // 新增属性，用于指定 label 字段名
    labelField: {
      type: String,
      default: 'itemName',
    },
    code: {
      type: String,
      default: undefined,
    },
  })

  const emit = defineEmits(['update:modelValue', 'change'])

  // 响应式状态
  const loading = ref(false)
  const searchKeyword = ref('')
  const hasMore = ref(true)
  const options = ref([])
  const innerValue = ref(props.mode === 'multiple' ? (Array.isArray(props.modelValue) ? props.modelValue : []) : props.modelValue)

  // 分页配置
  const pagination = reactive({
    current: 1,
    pageSize: 10,
    total: 0,
  })
  const querySubDataForm = reactive({})
  const getIdByCode = async () => {
    if (props.code) {
      const param = {
        code: props.code,
      }
      const queryResult = await dataDictionariesApi.findCode(param)
      querySubDataForm.dictId = queryResult.data.id
    }
  }

  // 核心请求方法
  const query = async () => {
    if (loading.value || !hasMore.value) {
      return
    }
    if (isEmpty(DICT[props.code])) {
      await getIdByCode()
      loading.value = true
      try {
        const params = {
          ...props.queryParams,
          [props.queryParamKey]: searchKeyword.value,
          dictId: querySubDataForm.dictId,
          sortFields: [
            {
              field: 'num',
              order: 'asc',
            },
          ],
          pageNo: pagination.current,
          pageSize: pagination.pageSize,
        }
        const rawRes = await dataSubDictionariesApi.queryPage(params)
        const { data, total } = props.responseAdapter(rawRes)
        const resData = data.map((item) => {
          item.disabled = item.status === ZZB_ENABLE_STATUS_ENUM.DISABLE_STATUS.value
          return {
            ...item,
            value: item[props.valueField],
            label: item[props.labelField],
          }
        })
        options.value = pagination.current === 1 ? resData : [...options.value, ...resData]
        pagination.total = total
        hasMore.value = options.value.length < total
        pagination.current++
      } catch (error) {
        message.error(' 数据加载失败')
      } finally {
        loading.value = false
      }
    } else {
      options.value = DICT[props.code]
    }
  }

  // 事件处理
  const handleSearch = debounce((value) => {
    searchKeyword.value = value
    pagination.current = 1
    options.value = []
    hasMore.value = true
    loading.value = true
    query()
  }, 500)

  const handlePopupScroll = debounce((e) => {
    const { scrollTop, clientHeight, scrollHeight } = e.target
    if (scrollHeight - (scrollTop + clientHeight) < 10 && hasMore.value) {
      query()
    }
  }, 200)

  const handleValueChange = (value) => {
    // 打印选择的值
    innerValue.value = value
    emit('update:modelValue', value)
    emit('change', value)
  }

  // 初始化加载
  onMounted(() => {
    query()
  })

  // 监听父组件值变化
  watch(
    () => props.modelValue,
    (newVal) => {
      innerValue.value = props.mode === 'multiple' ? (Array.isArray(newVal) ? newVal : []) : newVal
    },
  )
  // 监听 queryParams 变化
  watch(
    () => props.queryParams,
    (newParams) => {
      // 重置分页参数并重新查询
      pagination.current = 1
      options.value = []
      hasMore.value = true
      query()
    },
    { deep: true },
  )
  defineExpose({
    query,
    innerValue,
    options,
  })
</script>
